#include "application_registrar.h"

// Application Services
#include "application/map/map_application_service.h"
#include "application/vehicle/vehicle_service.h"
#include "application/vehicle/vehicle_operation_dispatcher.h"
#include "application/vehicle/vehicle_initializer.h"
#include "application/dispatcher/dispatcher_service.h"
#include "application/task/task_service.h"
#include "application/simulation/simulation_service.h"

// Infrastructure Services (only in .cpp file to maintain clean architecture)
#include "infrastructure/map/map_service.h"
#include "infrastructure/services/common_service.h"
#include "infrastructure/map/map_extend_loader.h"

using namespace infrastructure::services;
using namespace bootstrap::factories;
using namespace application::vehicle;

namespace bootstrap {
namespace registrars {

ApplicationRegistrar::ApplicationRegistrar(std::shared_ptr<ServiceContainer> container)
    : BaseRegistrar(container, "ApplicationRegistrar")
{
}

void ApplicationRegistrar::doRegisterServices()
{
    logInfo("开始注册应用层服务");

    // 注册车辆管理服务
    registerVehicleServices();

    // 注册仿真服务
    registerSimulationService();

    // 注册其他服务
    registerOtherServices();

    logInfo("应用层服务注册完成");
}

void ApplicationRegistrar::doInitializeServices()
{
    logInfo("开始初始化应用层服务");

    // 初始化地图应用服务
    safeInitializeService<application::MapApplicationService>("地图应用服务", true);

    // 初始化仿真服务（如果启用）
    initializeSimulationService();

    // 初始化车辆服务
    safeInitializeService<VehicleOperationDispatcher>("车辆操作分派器", true);
    safeInitializeService<VehicleService>("车辆服务", true);

    // 初始化 AGV（从配置文件，包括仿真车辆）
    initializeVehicles();

    // 初始化调度服务（可选初始化，主要依赖注入即可）
    safeInitializeService<application::dispatcher::DispatcherService>("调度服务", false);

    // 初始化任务服务并启动
    initializeTaskService();

    // 启动仿真引擎（如果启用）
    startSimulationEngine();

    logInfo("应用层服务初始化完成");
}

void ApplicationRegistrar::registerVehicleServices()
{
    logInfo("注册车辆管理服务");

    // ================== 车辆操作分派器注册 ==================
    auto dispatcherFactory = [](ServiceContainer& container) {
        return std::make_shared<VehicleOperationDispatcher>();
    };

    addRegistration(
        std::move(registerService<VehicleOperationDispatcher, VehicleOperationDispatcher>()
            .withDescription("车辆操作分派器 - 分派不同类型车辆的命令")
            .useCustomFactory(dispatcherFactory))
    );

    // ================== 车辆服务注册 ==================
    auto vehicleServiceFactory = [](ServiceContainer& container) {
        auto commonService = container.resolve<CommonService>();
        auto dispatcher = container.resolve<VehicleOperationDispatcher>();
        auto mapAppService = container.resolve<application::MapApplicationService>();

        if (!commonService) {
            throw std::runtime_error("车辆服务依赖解析失败: CommonService不可用");
        }

        if (!dispatcher) {
            throw std::runtime_error("车辆服务依赖解析失败: VehicleOperationDispatcher不可用");
        }

        if (!mapAppService) {
            throw std::runtime_error("车辆服务依赖解析失败: MapApplicationService不可用");
        }

        return std::make_shared<VehicleService>(commonService, dispatcher, mapAppService);
    };

    addRegistration(
        std::move(registerService<VehicleService, VehicleService>()
            .withDescription("车辆服务 - AGV 管理和状态监控")
            .useCustomFactory(vehicleServiceFactory))
    );

    logInfo("车辆管理服务注册完成");
}

void ApplicationRegistrar::registerSimulationService()
{
    logInfo("注册仿真服务");

    // ================== 仿真服务注册 ==================
    auto simulationServiceFactory = [](ServiceContainer& container) {
        auto mapService = container.resolve<application::MapApplicationService>();
        auto commonService = container.resolve<CommonService>();

        if (!mapService) {
            throw std::runtime_error("仿真服务依赖解析失败: MapApplicationService不可用");
        }

        if (!commonService) {
            throw std::runtime_error("仿真服务依赖解析失败: CommonService不可用");
        }

        auto logger = commonService->getLogger("SimulationService");
        return std::make_shared<application::simulation::SimulationService>(
            mapService,
            logger);
    };

    addRegistration(
        std::move(registerService<application::simulation::SimulationService, application::simulation::SimulationService>()
            .withDescription("仿真服务 - AGV仿真引擎和物理模拟")
            .useCustomFactory(simulationServiceFactory))
    );

    logInfo("仿真服务注册完成");
}

void ApplicationRegistrar::initializeVehicles()
{
    logInfo("开始初始化 AGV");

    try {
        auto commonService = m_container->resolve<CommonService>();
        auto vehicleService = m_container->resolve<VehicleService>();
        auto simulationService = m_container->resolve<application::simulation::SimulationService>();

        if (!commonService || !vehicleService) {
            logError("无法解析车辆服务或通用服务");
            return;
        }

        // 创建初始化器
        auto initializer = std::make_shared<VehicleInitializer>(commonService, vehicleService);

        // 设置仿真服务（如果可用）
        if (simulationService) {
            initializer->setSimulationService(simulationService);
            logInfo("仿真服务已注入到车辆初始化器");
        }

        // 从配置文件初始化所有车辆（包括仿真车辆）
        bool success = initializer->initializeVehiclesFromConfig();

        if (success) {
            logInfo("AGV 初始化成功");
        } else {
            logWarning("AGV 初始化失败或部分失败");
        }

    } catch (const std::exception& e) {
        logError(QString("AGV 初始化异常: %1").arg(e.what()));
    }
}

void ApplicationRegistrar::initializeTaskService()
{
    logInfo("开始初始化任务服务");

    try {
        auto taskService = m_container->resolve<application::task::TaskService>();
        auto mapAppService = m_container->resolve<application::MapApplicationService>();

        if (!taskService) {
            logError("无法解析任务服务");
            return;
        }

        // 连接呼叫器信号到任务服务
        if (mapAppService) {
            auto callerManager = mapAppService->getCallerManager(mapAppService->getCurrentFloor());
            if (callerManager) {
                QObject::connect(
                    callerManager.get(),
                    &application::caller::CallerManager::buttonPressed,
                    callerManager.get(),
                    [taskService](const application::caller::CallerMessage& msg) {
                        taskService->handleCallerTriggeredTask(msg);
                    });
                logInfo("呼叫器信号已连接到任务服务");
            } else {
                logWarning("未找到呼叫器管理器，跳过信号连接");
            }
        }

        // 启动任务服务（开始执行任务）
        taskService->start();

        logInfo("任务服务初始化并启动成功");

    } catch (const std::exception& e) {
        logError(QString("任务服务初始化异常: %1").arg(e.what()));
    }
}

void ApplicationRegistrar::initializeSimulationService()
{
    logInfo("开始初始化仿真服务");

    try {
        auto simulationService = m_container->resolve<application::simulation::SimulationService>();
        auto commonService = m_container->resolve<CommonService>();

        if (!simulationService) {
            logInfo("仿真服务不可用，跳过初始化");
            return;
        }

        if (!commonService) {
            logWarning("无法解析 CommonService，跳过仿真服务初始化");
            return;
        }

        // 读取配置检查是否启用
        auto config = commonService->configuration();
        auto simConfig = config->getSection("simulation");

        if (simConfig.has_value()) {
            bool enabled = simConfig.value()->getBool("enabled", false);
            simulationService->setEnabled(enabled);

            if (enabled) {
                simulationService->initialize();
                logInfo("仿真服务初始化完成（已启用）");
            } else {
                logInfo("仿真模式未启用");
            }
        } else {
            logInfo("未找到仿真配置，默认禁用仿真");
        }

    } catch (const std::exception& e) {
        logError(QString("仿真服务初始化异常: %1").arg(e.what()));
    }
}

void ApplicationRegistrar::startSimulationEngine()
{
    logInfo("启动仿真引擎");

    try {
        auto simulationService = m_container->resolve<application::simulation::SimulationService>();

        if (!simulationService) {
            logInfo("仿真服务不可用，跳过引擎启动");
            return;
        }

        if (!simulationService->isEnabled()) {
            logInfo("仿真未启用，跳过引擎启动");
            return;
        }

        // 启动仿真引擎
        simulationService->play();
        logInfo("仿真引擎已启动");

    } catch (const std::exception& e) {
        logError(QString("仿真引擎启动异常: %1").arg(e.what()));
    }
}

void ApplicationRegistrar::registerOtherServices()
{
    logInfo("注册其他应用服务");

    // ================== 地图应用服务注册 ==================
    auto mapAppServiceFactory = [](ServiceContainer& container) {
        auto mapService = container.resolve<infrastructure::MapService>();
        auto commonService = container.resolve<infrastructure::services::CommonService>();

        if (!mapService) {
            throw std::runtime_error("地图应用服务依赖解析失败: MapService不可用");
        }

        if (!commonService) {
            throw std::runtime_error("地图应用服务依赖解析失败: CommonService不可用");
        }

        auto extendLoaderLogger = commonService->getLogger("MapExtendLoader");
        auto extendLoader = std::make_shared<infrastructure::MapExtendLoader>(extendLoaderLogger);
        return std::make_shared<application::MapApplicationService>(
            mapService,
            commonService,
            extendLoader);
    };

    addRegistration(
        std::move(registerService<application::MapApplicationService, application::MapApplicationService>()
            .withDescription("地图应用服务 - 地图数据和路径管理")
            .useCustomFactory(mapAppServiceFactory))
    );

    logInfo("地图应用服务注册完成");

    // TODO: 可以根据需要添加其他服务
    // 如：路径规划服务、报表服务等

    logInfo("其他应用服务注册完成");

    // ================== 调度服务注册 ==================
    // DispatcherService depends on VehicleService, MapApplicationService, CommonService
    auto dispatcherServiceFactory = [](ServiceContainer& container) {
        auto vehicleService = container.resolve<application::vehicle::VehicleService>();
        auto mapAppService = container.resolve<application::MapApplicationService>();
        auto commonService = container.resolve<infrastructure::services::CommonService>();

        if (!vehicleService || !mapAppService || !commonService) {
            throw std::runtime_error("调度服务依赖解析失败: VehicleService/MapApplicationService/CommonService 不可用");
        }

        return std::make_shared<application::dispatcher::DispatcherService>(
            vehicleService,
            mapAppService,
            commonService
        );
    };

    addRegistration(
        std::move(registerService<application::dispatcher::DispatcherService, application::dispatcher::DispatcherService>()
            .withDescription("调度服务 - AGV调度、路径规划、区域管理")
            .useCustomFactory(dispatcherServiceFactory))
    );

    logInfo("调度服务注册完成");

    // ================== 任务服务注册 ==================
    // TaskService depends on VehicleService, DispatcherService, MapApplicationService, CommonService
    auto taskServiceFactory = [](ServiceContainer& container) {
        auto vehicleService = container.resolve<application::vehicle::VehicleService>();
        auto dispatcherService = container.resolve<application::dispatcher::DispatcherService>();
        auto mapAppService = container.resolve<application::MapApplicationService>();
        auto commonService = container.resolve<infrastructure::services::CommonService>();

        if (!vehicleService || !dispatcherService || !mapAppService || !commonService) {
            throw std::runtime_error("任务服务依赖解析失败: VehicleService/DispatcherService/MapApplicationService/CommonService 不可用");
        }

        return std::make_shared<application::task::TaskService>(
            vehicleService,
            dispatcherService,
            mapAppService,
            commonService
        );
    };

    addRegistration(
        std::move(registerService<application::task::TaskService, application::task::TaskService>()
            .withDescription("任务服务 - 任务创建、调度、执行管理")
            .useCustomFactory(taskServiceFactory))
    );

    logInfo("任务服务注册完成");
}

} // namespace registrars
} // namespace bootstrap
